<!DOCTYPE html>






  


<html class="theme-next mist use-motion" lang="zh-CN">
<head>
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.2.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.2.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.2.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.2.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.2.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.2.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="排序算法（Sorting algorithm）是计算机科学最古老、最基本的课题之一。目前，最常见的排序算法大概有七八种  其中，合并算法、快速排序算法是实际应用中最多的  插入排序 打扑克抓牌后怎么码牌？抓一张跟手里的牌比较一下，然后插入合适的位置，其实这就是插入排序  原理它将数组分成“已排序”和“未排序”两部分，“已排序”的部分只有一个元素，然后将它后面一个元素从“未排序”部分插入“已排序”部">
<meta name="keywords" content="算法,入门">
<meta property="og:type" content="article">
<meta property="og:title" content="排序算法">
<meta property="og:url" content="http://pentay.gitee.com/2018/05/06/algorithm-sorting/index.html">
<meta property="og:site_name" content="路边摊">
<meta property="og:description" content="排序算法（Sorting algorithm）是计算机科学最古老、最基本的课题之一。目前，最常见的排序算法大概有七八种  其中，合并算法、快速排序算法是实际应用中最多的  插入排序 打扑克抓牌后怎么码牌？抓一张跟手里的牌比较一下，然后插入合适的位置，其实这就是插入排序  原理它将数组分成“已排序”和“未排序”两部分，“已排序”的部分只有一个元素，然后将它后面一个元素从“未排序”部分插入“已排序”部">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://pentay.gitee.com/images/algorithm-sorting.png">
<meta property="og:updated_time" content="2018-05-07T03:29:00.618Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="排序算法">
<meta name="twitter:description" content="排序算法（Sorting algorithm）是计算机科学最古老、最基本的课题之一。目前，最常见的排序算法大概有七八种  其中，合并算法、快速排序算法是实际应用中最多的  插入排序 打扑克抓牌后怎么码牌？抓一张跟手里的牌比较一下，然后插入合适的位置，其实这就是插入排序  原理它将数组分成“已排序”和“未排序”两部分，“已排序”的部分只有一个元素，然后将它后面一个元素从“未排序”部分插入“已排序”部">
<meta name="twitter:image" content="http://pentay.gitee.com/images/algorithm-sorting.png">






  <link rel="canonical" href="http://pentay.gitee.com/2018/05/06/algorithm-sorting/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>排序算法 | 路边摊</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript><!-- hexo-inject:begin --><!-- hexo-inject:end -->

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <!-- hexo-inject:begin --><!-- hexo-inject:end --><div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">路边摊</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
    </ul>
  

  
    

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://pentay.gitee.com/2018/05/06/algorithm-sorting/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="易言">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="路边摊">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">排序算法
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-05-06 07:45:12" itemprop="dateCreated datePublished" datetime="2018-05-06T07:45:12+08:00">2018-05-06</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-05-07 11:29:00" itemprop="dateModified" datetime="2018-05-07T11:29:00+08:00">2018-05-07</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/算法/" itemprop="url" rel="index"><span itemprop="name">算法</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>排序算法（Sorting algorithm）是计算机科学最古老、最基本的课题之一。目前，最常见的排序算法大概有七八种</p>
<p><img src="/images/algorithm-sorting.png" alt=""></p>
<p>其中，<code>合并算法</code>、<code>快速排序算法</code>是实际应用中最多的</p>
<hr>
<h1 id="插入排序"><a href="#插入排序" class="headerlink" title="插入排序"></a>插入排序</h1><blockquote>
<p>打扑克抓牌后怎么码牌？抓一张跟手里的牌比较一下，然后插入合适的位置，其实这就是<code>插入排序</code></p>
</blockquote>
<h2 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h2><p>它将数组分成“已排序”和“未排序”两部分，“已排序”的部分只有一个元素，<br>然后将它后面一个元素从“未排序”部分插入“已排序”部分，从而“已排序”部分增加一个元素，“未排序”部分减少一个元素。<br>以此类推，完成全部排序。</p>
<h2 id="举例"><a href="#举例" class="headerlink" title="举例"></a>举例</h2><p>以对数组[3, 2, 4, 5, 1] 进行从小到大排序为例，步骤如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">将数组分成[3]和[2, 4, 5, 1]两部分，前者是已排序的，后者是未排序的。</span><br><span class="line">取出未排序部分的第一个元素“2”，与已排序部分最后一个元素“3”比较，因为2小于3，所以2排在3前面，整个数组变成[2, 3]和[4, 5, 1]两部分。</span><br><span class="line">取出未排序部分的第一个元素“4”，与已排序部分最后一个元素“3”比较，因为4大于3，所以4排在3后面，整个数组变成[2, 3, 4]和[5, 1]两部分。</span><br><span class="line">取出未排序部分的第一个元素“5”，与已排序部分最后一个元素“4”比较，因为5大于4，所以5排在4后面，整个数组变成[2, 3, 4, 5]和[1]两部分。</span><br><span class="line">取出未排序部分的第一个元素“1”，与已排序部分最后一个元素“5”比较，因为1小于5，所以再与前一个元素“4”比较；因为1小于4，再与前一个元素“3”比较；因为1小于3，再与前一个元素“2”比较；因为小于1小于2，所以“1”排在2的前面，整个数组变成[1, 2, 3, 4, 5]。</span><br></pre></td></tr></table></figure></p>
<h2 id="JavaScript实现"><a href="#JavaScript实现" class="headerlink" title="JavaScript实现"></a>JavaScript实现</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">function insertionSort(myArray) &#123;</span><br><span class="line"></span><br><span class="line">    var len     = myArray.length,     // 数组的长度</span><br><span class="line">        value,                      // 当前比较的值</span><br><span class="line">        i,                          // 未排序部分的当前位置</span><br><span class="line">        j;                          // 已排序部分的当前位置</span><br><span class="line"></span><br><span class="line">    for (i=0; i &lt; len; i++) &#123;</span><br><span class="line"></span><br><span class="line">        // 储存当前位置的值</span><br><span class="line">        value = myArray[i];</span><br><span class="line"></span><br><span class="line">        /*</span><br><span class="line">         * 当已排序部分的当前元素大于value，</span><br><span class="line">         * 就将当前元素向后移一位，再将前一位与value比较</span><br><span class="line">         */</span><br><span class="line">        for (j=i-1; j &gt; -1 &amp;&amp; myArray[j] &gt; value; j--) &#123;</span><br><span class="line">            myArray[j+1] = myArray[j];</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        myArray[j+1] = value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    return myArray;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="交换排序"><a href="#交换排序" class="headerlink" title="交换排序"></a>交换排序</h1><p>顾名思义，就是通过交换元素位置来进行排序，有两种：</p>
<ul>
<li>冒泡排序</li>
<li>快速排序</li>
</ul>
<h2 id="冒泡排序"><a href="#冒泡排序" class="headerlink" title="冒泡排序"></a>冒泡排序</h2><blockquote>
<p>顾名思义，冒泡一样，把较大的泡泡或者较小的泡泡会往某个方向移动，直到所有的泡泡按次序排好</p>
</blockquote>
<p>冒泡排序（Bubble Sort）是最易懂的排序算法，但是效率较低，生产环境中很少使用。</p>
<h3 id="原理："><a href="#原理：" class="headerlink" title="原理："></a>原理：</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1. 比较相邻的元素，如果第一个比第二个大，就交换他们两个。</span><br><span class="line">2. 循环操作第1步，直到完整排序</span><br></pre></td></tr></table></figure>
<h3 id="举例："><a href="#举例：" class="headerlink" title="举例："></a>举例：</h3><p>以对数组[3, 2, 4, 5, 1]进行从小到大排序为例，步骤如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">a. 第一位的“3”与第二位的“2”进行比较，3大于2，互换位置，数组变成[2, 3, 4, 5, 1]。</span><br><span class="line">b. 第二位的“3”与第三位的“4”进行比较，3小于4，数组不变。</span><br><span class="line">c. 第三位的“4”与第四位的“5”进行比较，4小于5，数组不变。</span><br><span class="line">d. 第四位的“5”与第五位的“1”进行比较，5大于1，互换位置，数组变成[2, 3, 4, 1, 5]。</span><br><span class="line">e. 第一轮排序完成，可以看到最后一位的5，已经是正确的数了。</span><br><span class="line">f. 再对剩下的数[2, 3, 4, 1]重复这个过程，每一轮都会在本轮最后一位上出现正确的数。直至剩下最后一个位置，所有排序结束。</span><br></pre></td></tr></table></figure></p>
<h3 id="javascript实现"><a href="#javascript实现" class="headerlink" title="javascript实现"></a>javascript实现</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">swap</span>(<span class="params">myArr, a, b</span>) </span>&#123; <span class="comment">//交换函数，封装交换操作</span></span><br><span class="line">    <span class="keyword">var</span> temp = myArr[a];</span><br><span class="line">    myArr[a] = myArr[b];</span><br><span class="line">    myArr[b] = temp;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bubbleSort</span>(<span class="params">myArr</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> len = myArr.length,</span><br><span class="line">            i, j,stop;</span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; len; i++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (j = <span class="number">0</span>, stop = len - <span class="number">1</span> - i; j &lt; stop; j++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (myArr[j] &gt; myArr[j + <span class="number">1</span>]) &#123;</span><br><span class="line">                swap(myArr, myArr[j], myArr[j + <span class="number">1</span>]);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> myArr;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="快速排序"><a href="#快速排序" class="headerlink" title="快速排序"></a>快速排序</h2><p>快速排序（Quick Sort）是<code>公认最快的排序算法之一</code>，有着广泛的应用，采用了<strong><code>分治法</code></strong>的思想，所以也称<code>划分交换排序</code></p>
<p>快速排序算法的平均时间复杂度为 $O(N \log N)$。快排的最差情况为序列完全有序，此时快排退化为冒泡排序，时间复杂度为 $O(N^2)$ 。</p>
<h3 id="原理-1"><a href="#原理-1" class="headerlink" title="原理"></a>原理</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1. 从数列中取出一个数作为基准数（枢轴，pivot）。</span><br><span class="line">2. 将数组进行划分(partition)，将比基准数大的元素都移至枢轴右边，将小于等于基准数的元素都移至枢轴左边。</span><br><span class="line">3. 再对左右的子区间重复第二步的划分操作，直至每个子区间只有一个元素。</span><br></pre></td></tr></table></figure>
<h3 id="举例-1"><a href="#举例-1" class="headerlink" title="举例"></a>举例</h3><p>以对数组[3, 2, 4, 5, 1]进行从小到大排序为例，步骤如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">a. 选择中间值“4”作为“支点”。</span><br><span class="line">b. 第一个元素3小于4，左侧指针向后移动一位；第二个元素2小于4，左侧指针向后移动一位；第三个元素4等于4，左侧指针停在这个位置（数组的第2位）。</span><br><span class="line">c. 倒数第一个元素1小于4，右侧指针停在这个位置（数组的第4位）。</span><br><span class="line">d. 左侧指针的位置（2）小于右侧指针的位置（4），两个位置的值互换，数组变成[3, 2, 1, 5, 4]。</span><br><span class="line">e. 左侧指针向后移动一位，第四个元素5大于4，左侧指针停在这个位置（数组的第3位）。</span><br><span class="line">f. 右侧指针向前移动一位，第四个元素5大于4，右侧指针移动向前移动一位，第三个元素1小于4，右侧指针停在这个位置（数组的第3位）。</span><br><span class="line">g. 左侧指针的位置（3）大于右侧指针的位置（2），本次排序结束。</span><br><span class="line">h. 对 [3, 2, 1]和[5, 4]两部分各自不断重复上述步骤，直到排序完成。</span><br></pre></td></tr></table></figure></p>
<h3 id="javascript实现："><a href="#javascript实现：" class="headerlink" title="javascript实现："></a>javascript实现：</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">swap</span>(<span class="params">myArr, a, b</span>) </span>&#123; <span class="comment">//交换函数，封装交换操作</span></span><br><span class="line">    <span class="keyword">var</span> temp = myArr[a];</span><br><span class="line">    myArr[a] = myArr[b];</span><br><span class="line">    myArr[b] = temp;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">patition</span>(<span class="params">myArr, left, right</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> pivot = myArr[<span class="built_in">Math</span>.floor((left + right) / <span class="number">2</span>)],</span><br><span class="line">            i = left,</span><br><span class="line">            j = right;</span><br><span class="line">    <span class="keyword">while</span> (i &lt;= j) &#123;</span><br><span class="line">        <span class="keyword">while</span> (myArr[i] &lt; pivot) &#123;</span><br><span class="line">            i++;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span> (myArr[j] &gt; pivot) &#123;</span><br><span class="line">            j--;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (i &lt;= j) &#123;</span><br><span class="line">            swapN(myArr, i, j);</span><br><span class="line">            i++;</span><br><span class="line">            j++;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> i;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">quickSort</span>(<span class="params">myArr, left, right</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (myArr.length &lt; <span class="number">2</span>) <span class="keyword">return</span> myArr;</span><br><span class="line"></span><br><span class="line">    left = (<span class="keyword">typeof</span> left !== <span class="string">'number'</span> ? <span class="number">0</span> : left);</span><br><span class="line">    right = (<span class="keyword">typeof</span> right !== <span class="string">'number'</span> ? myArr.length - <span class="number">1</span> : right);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> index = patition(myArr, left, right);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (left &lt; index - <span class="number">1</span>) &#123;</span><br><span class="line">        quickSort(myArr, left, index - <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (index &lt; right) &#123;</span><br><span class="line">        quickSort(myArr, index, right);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> myArr;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="选择排序"><a href="#选择排序" class="headerlink" title="选择排序"></a>选择排序</h1><p>选择排序（Selection Sort）与冒泡排序类似，也是依次对相邻的数进行两两比较。也称<code>直接选择排序</code></p>
<h2 id="原理-2"><a href="#原理-2" class="headerlink" title="原理"></a>原理</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">从数列中取出一个数作为基准数（枢轴，pivot）。</span><br><span class="line">依次取数跟基准数比较，循环找出最小/最大值，然后交换</span><br><span class="line">循环前两步</span><br></pre></td></tr></table></figure>
<h2 id="举例-2"><a href="#举例-2" class="headerlink" title="举例"></a>举例</h2><p>以对数组[3, 2, 4, 5, 1] 进行从小到大排序为例，步骤如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">假定第一位的“3”是最小值。</span><br><span class="line"></span><br><span class="line">最小值“3”与第二位的“2”进行比较，2小于3，所以新的最小值是第二位的“2”。</span><br><span class="line"></span><br><span class="line">最小值“2”与第三位的“4”进行比较，2小于4，最小值不变。</span><br><span class="line"></span><br><span class="line">最小值“2”与第四位的“5”进行比较，2小于5，最小值不变。</span><br><span class="line"></span><br><span class="line">最小值“2”与第五位的“1”进行比较，1小于2，所以新的最小值是第五位的“1”。</span><br><span class="line"></span><br><span class="line">第五位的“1”与第一位的“3”互换位置，数组变为[1, 2, 4, 5, 3]</span><br></pre></td></tr></table></figure></p>
<h2 id="javascript实现-1"><a href="#javascript实现-1" class="headerlink" title="javascript实现"></a>javascript实现</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">swap</span>(<span class="params">myArr, a, b</span>) </span>&#123; <span class="comment">//交换函数，封装交换操作</span></span><br><span class="line">    <span class="keyword">var</span> temp = myArr[a];</span><br><span class="line">    myArr[a] = myArr[b];</span><br><span class="line">    myArr[b] = temp;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">selectionSort</span>(<span class="params">myArray</span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> min, len = myArray.length;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (i=<span class="number">0</span>; i &lt; len; i++)&#123;</span><br><span class="line">        <span class="comment">// 将当前位置设为最小值</span></span><br><span class="line">        min = i;</span><br><span class="line">        <span class="comment">// 检查数组其余部分是否更小</span></span><br><span class="line">        <span class="keyword">for</span> (j=i+<span class="number">1</span>; j &lt; len; j++)&#123;</span><br><span class="line">            <span class="keyword">if</span> (myArray[j] &lt; myArray[min])&#123;</span><br><span class="line">                min = j;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 如果当前位置不是最小值，将其换为最小值</span></span><br><span class="line">        <span class="keyword">if</span> (i != min)&#123;</span><br><span class="line">            swap(myArray, i, min);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> myArray;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="合并排序（Merge-sort）"><a href="#合并排序（Merge-sort）" class="headerlink" title="合并排序（Merge sort）"></a>合并排序（Merge sort）</h1><h2 id="原理-3"><a href="#原理-3" class="headerlink" title="原理"></a>原理</h2><p>将数组拆开，分成n个只有一个元素的数组，然后不断地两两合并，直到全部排序完成。</p>
<h2 id="范例"><a href="#范例" class="headerlink" title="范例"></a>范例</h2><p>以对数组[3, 2, 4, 5, 1] 进行从小到大排序为例，步骤如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">将数组分成[3, 2, 4]和[5, 1]两部分。</span><br><span class="line">将[3, 2, 4]分成[3, 2]和[4]两部分。</span><br><span class="line">将[3, 2]分成[3]和[2]两部分，然后合并成[2, 3]。</span><br><span class="line">将[2, 3]和[4]合并成[2, 3, 4]。</span><br><span class="line">将[5, 1]分成[5]和[1]两部分，然后合并成[1, 5]。</span><br><span class="line">将[2, 3, 4]和[1, 5]合并成[1, 2, 3, 4, 5]。</span><br></pre></td></tr></table></figure></p>
<h2 id="JavaScript实现-1"><a href="#JavaScript实现-1" class="headerlink" title="JavaScript实现"></a>JavaScript实现</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">merge</span>(<span class="params">left, right</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> result  = [],</span><br><span class="line">        il      = <span class="number">0</span>,</span><br><span class="line">        ir      = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> (il &lt; left.length &amp;&amp; ir &lt; right.length)&#123;</span><br><span class="line">        <span class="keyword">if</span> (left[il] &lt; right[ir])&#123;</span><br><span class="line">            result.push(left[il++]);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            result.push(right[ir++]);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> result.concat(left.slice(il)).concat(right.slice(ir));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h1><p><a href="https://javascript.ruanyifeng.com/library/sorting.html" target="_blank" rel="noopener">JavaScript 标准参考教程（alpha）</a></p>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/算法/" rel="tag"># 算法</a>
          
            <a href="/tags/入门/" rel="tag"># 入门</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/05/05/base/" rel="next" title="编程基础-算法入门">
                <i class="fa fa-chevron-left"></i> 编程基础-算法入门
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/05/07/algorithm-search/" rel="prev" title="算法-查找入门">
                算法-查找入门 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">易言</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">15</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">3</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">7</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#插入排序"><span class="nav-number">1.</span> <span class="nav-text">插入排序</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#原理"><span class="nav-number">1.1.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#举例"><span class="nav-number">1.2.</span> <span class="nav-text">举例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JavaScript实现"><span class="nav-number">1.3.</span> <span class="nav-text">JavaScript实现</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#交换排序"><span class="nav-number">2.</span> <span class="nav-text">交换排序</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#冒泡排序"><span class="nav-number">2.1.</span> <span class="nav-text">冒泡排序</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#原理："><span class="nav-number">2.1.1.</span> <span class="nav-text">原理：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#举例："><span class="nav-number">2.1.2.</span> <span class="nav-text">举例：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#javascript实现"><span class="nav-number">2.1.3.</span> <span class="nav-text">javascript实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#快速排序"><span class="nav-number">2.2.</span> <span class="nav-text">快速排序</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#原理-1"><span class="nav-number">2.2.1.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#举例-1"><span class="nav-number">2.2.2.</span> <span class="nav-text">举例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#javascript实现："><span class="nav-number">2.2.3.</span> <span class="nav-text">javascript实现：</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#选择排序"><span class="nav-number">3.</span> <span class="nav-text">选择排序</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#原理-2"><span class="nav-number">3.1.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#举例-2"><span class="nav-number">3.2.</span> <span class="nav-text">举例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#javascript实现-1"><span class="nav-number">3.3.</span> <span class="nav-text">javascript实现</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#合并排序（Merge-sort）"><span class="nav-number">4.</span> <span class="nav-text">合并排序（Merge sort）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#原理-3"><span class="nav-number">4.1.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#范例"><span class="nav-number">4.2.</span> <span class="nav-text">范例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JavaScript实现-1"><span class="nav-number">4.3.</span> <span class="nav-text">JavaScript实现</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考链接"><span class="nav-number">5.</span> <span class="nav-text">参考链接</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">易言</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Mist</a> v6.2.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.2.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.2.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.2.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.2.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.2.0"></script>



  



	





  





  










  





  

  

  

  
  

  
  

  
    
      <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/mathjax@2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script><!-- hexo-inject:begin --><!-- Begin: Injected MathJax -->
<script type="text/x-mathjax-config">
  MathJax.Hub.Config("");
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
      all[i].SourceElement().parentNode.className += ' has-jax';
    }
  });
</script>

<script type="text/javascript" src="">
</script>
<!-- End: Injected MathJax -->
<!-- hexo-inject:end -->

    
  


  
  

  

  

  

  

  

</body>
</html>
